package com.res.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.res.entity.Department;
import com.res.repository.DepartmentRepository;
import com.res.service.DepartmentService;
@Service
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentRepository departmentRepository;
	@Override
	public Page<Department> findByDname(Department d, Pageable pageable) {
		// TODO Auto-generated method stub
		return departmentRepository.findAll(get(d), pageable);
	}

	private Specification<Department> get(Department d) {
		// TODO Auto-generated method stub
		return new Specification<Department>() {
			
			@Override
			public Predicate toPredicate(Root<Department> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if(!StringUtils.isEmpty(d.getDname())) {
				expressions.add(criteriaBuilder.like(root.get("dname"), "%"+d.getDname()+"%"));
				}
				return predicate;
			}
		};
	}

	@Override
	public Department AddandUpdateDepartment(Department d) {
		// TODO Auto-generated method stub
		return departmentRepository.saveAndFlush(d);
	}

	@Override
	public void deleteDepartment(Integer did) {
		// TODO Auto-generated method stub
		departmentRepository.deleteById(did);

	}

}
